using System;
using System.Collections;
using System.ComponentModel;
using System.Web.UI.WebControls;

namespace GoodStuff.Web.Controls
{
	/// <summary>
	/// Summary description for CaptchaValidator.
	/// </summary>
	public class CaptchaValidator : BaseValidator
	{
		private string _captchaImage;

		/// <summary>
		/// The name of the control that contains the challenge.
		/// </summary>
		/// <remarks>
		/// A special type converter is used to allow a selection in the designer.
		/// </remarks>
		[TypeConverter(typeof(Design.CaptchaImageControlConverter))]
		[Category("Behavior")]
		public string CaptchaImage
		{
			get { return _captchaImage; }
			set { _captchaImage = value; }
		}

		/// <summary>
		/// Private helper function to convert the name of the challenge control
		/// into the control on the current form.
		/// </summary>
		private CaptchaImage AssociatedCaptchaImage
		{
			get
			{
				CaptchaImage captcha = NamingContainer.FindControl(CaptchaImage) as CaptchaImage;

				return captcha;
			}
		}

		protected override bool EvaluateIsValid()
		{
			string controlName = base.ControlToValidate;
			if (controlName != null)
			{
				string controlValue = base.GetControlValidationValue(controlName);
				if (controlValue != null && 
					((controlValue = controlValue.Trim()).Length > 0))
				{
					return AssociatedCaptchaImage.Authenticate(controlValue);
				}
			}
			return false;
		}

	}
}
